using Chaotic.DataBase.DBAccessLibrary.Common;
using Chaotic.DataBase.DBAccessLibrary.DBAccessLibrary;

namespace Chaotic.DataBase.DBAccessLibrary.Model;

[Serializable]
public class DBEntity : DataBaseEntity
{
	private DBConnectStatus _status;

	private ConnectionModel? _connectionSource;

	public DBConnectStatus Status
	{
		get => _status;
        set
		{
			_status = value;
			ChangeIcon();
			this.NotifyPropertyChanged((o) => o.Status);
		}
	}

	public ConnectionModel? ConnectionSource
	{
		get => _connectionSource;
        set
		{
			if (value != _connectionSource)
			{
				_connectionSource = value;
				this.NotifyPropertyChanged((o) => o.ConnectionSource);
			}
		}
	}

	public DBEntity(string? name)
		: base(name)
	{
		base.ImageUrl = "/Images/Tree/db.png";
	}

	private void ChangeIcon()
	{
		if (_status == DBConnectStatus.Connected)
		{
			base.ImageUrl = "/Images/Tree/btnConnect.png";
			SysCache.DBConnection = _connectionSource;
			if (base.ChildNodes.Count > 0)
			{
				SysCache.TableList = base.ChildNodes[0].ChildNodes.Cast<TableEntity>();
				SysCache.ViewList = base.ChildNodes[1].ChildNodes.Cast<ViewEntity>();
				SysCache.ProcList = base.ChildNodes[2].ChildNodes.Cast<ProcEntity>();
			}
		}
		else
		{
			base.ImageUrl = "/Images/Tree/btnUnConnect.png";
			SysCache.DBConnection = null;
			SysCache.TableList = null;
			SysCache.ViewList = null;
			SysCache.ProcList = null;
			SysCache.TypeList = null;

			ChildNodes.Clear();

        }
	}

	public override void ClearState()
	{
		if (SysCache.DBConnection != ConnectionSource)
		{
			DataBaseEntity?[] array = base.ChildNodes.ToArray();
			foreach (DataBaseEntity? item in array)
			{
				base.ChildNodes.Remove(item);
			}
		}
		else
		{
			base.ClearState();
		}
	}

	public override DataBaseEntity? Copy()
	{
		DBEntity? dBEntity = new DBEntity(base.Name)
        {
            ConnectionSource = ConnectionSource,
            IsExpanded = base.IsExpanded,
            IsSelected = base.IsSelected
        };
        DBEntity? dBEntity2 = dBEntity;
		Copy(dBEntity2);
		dBEntity2.ImageUrl = "/Images/Tree/btnUnConnect.png";
		return dBEntity2;
	}
}
